<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml" xml:lang="en">
<head>
<title>Kuch Bhi Kya !</title>

<link rel="stylesheet" type="text/css" href="/css/ui-darkness/jquery-ui-1.8.4.custom.css" />
<link rel="stylesheet" type="text/css" href="/css/play.css" />

<style>
  body {
    font-family: 'Trebuchet MS', Verdana, Arial, sans-serif;
    font-size: 12px;
    background-color: #D8DFEA;
    color: #333333;
  }
  .countdown {
    font-family: 'Comic Sans', Comic Sans MS;
    font-size: 45px;
    color: white;
    text-align: center;
  }
  .general {
    top: 50; 
    padding: 1%; 
    height: 250; 
    width: 98%; 
    position: absolute;
    background-color: black;
  }
  .headerarea {
    padding: 8 8 8 8; 
    height: 20; 
    width: 98%; 
    /*position: absolute;*/
    font-family: Arial, sans-serif;
    font-size: 14px;
    font-weight: bold;
    background-color: #3b5998; 
    color: white;
  } 
  .playarea {
    background-color: #3b5998; 
  } 
  .playarea_ol {
    z-index: 1;
    background-color: #3b5998; 
  } 
  .qaarea {
    top: 325; 
    height: 240; 
    font-family: Arial, sans-serif;
    font-size: 15px;
  }
  .debug-area {
    left: 500;
    width: 300;
    color: blue;
    position: absolute;
    display: block;
    z-index: 2;
  }
</style>

<script type="text/javascript" src="/js/swfobject.js"></script>    
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>    
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.4/jquery-ui.min.js"></script>    

<script type="text/javascript">

  var intTime = null;
  var ytplayer = null;
  var qList = new Array();
  var cntDown = 15;
  var currQ = new Object();
  var currIndex = 0;
  var timeout = null;
  var startIndex = 1;
  var maxResult = 10;
  var qListLength = 0; //length of the question list

  var UserInfo = new Object();
  UserInfo.level = 1;
  UserInfo.name = "";
  UserInfo.uid = 0;
  UserInfo.score = 0;
  UserInfo.hits = 0;
  UserInfo.miss = 0;
  UserInfo.currQ = 0;

  //jquery stuff
  $(function() {
    //init
    $(".debug-area").hide();
    $("#next").button();
    $("#choice").button();
    //getQList();
    //getYTList();
    $("#next").bind('click', startQ);
    $("#choice").hide();
    updateStatus();
  })

  function updateStatus() {
    UserInfo.level = Math.floor((UserInfo.score+1000)/1000);
    var tot = UserInfo.miss+UserInfo.hits;

    if(UserInfo.uid != 0) {
      $("#status").html("Hello, " + UserInfo.name);
      $("#status-score").html("Level " + UserInfo.level + "&nbsp;&nbsp; | &nbsp;&nbsp;Score: " + UserInfo.score+ "&nbsp;&nbsp; | &nbsp;&nbsp;Hits: " + UserInfo.hits + "/" + tot);
    }
    else {
      $("#status").html("Please login using your facebook account to keep track of your scores");
      $("#login-button").show();
    }
  }

  //Youtube stuff
  var params = { allowScriptAccess: "always", rel: "0", wmode: "opaque" };
  var atts = { id: "myytplayer" };
  swfobject.embedSWF("http://www.youtube.com/apiplayer?enablejsapi=1&version=3", 
                     "ytapiplayer", "100%", "240", "8", null, null, params, atts);

  function onYouTubePlayerReady(playerId) {
    ytplayer = document.getElementById("myytplayer");
    ytplayer.addEventListener("onStateChange", "onYTStateChange");
  }

  function onYTStateChange(newstate) {
    switch(newstate) {
      case -1:
        $("#debug1").html("unstarted\n");
        break;
      case 0:
        $("#debug1").html("ended");
        resetQ("Hit Play for the next Question");
        break;
      case 1:
        $("#debug1").html("playing\n");
        if(!timeout) {
          $("#debug").append("onYTStateChange: will stop after " +  currQ.playtime + "\n");
          timeout = setTimeout("stopQ()", currQ.playtime*1000); 
        }
        break;
      case 2:
        $("#debug1").html("paused");
        break;
      case 3:
        $("#debug1").html("buffering\n");
        break;
      case 4:
        $("#debug1").html("unknown 4");
        break;
      case 5:
        $("#debug1").html("cued");
        break;
      default:
        break;
    }
  }

  //fetch the most popular feed from YT and callback updateQList
  function getYTList() {

    var feed = 'most_popular';

    var h = document.getElementsByTagName('head').item(0);
    var s = document.createElement("script");
    s.type = "text/javascript";
    s.src="http://gdata.youtube.com/feeds/api/standardfeeds/" + feed + "?time=this_week&alt=json-in-script&callback=updateQList&max-results=" + maxResult + "&start-index=" + startIndex;
    h.appendChild(s);
    $("#debug").append("getYTList: url " + s.src + " \n");
    startIndex += maxResult;
  }

  //date,id,key,title,author,url,rating,hits,playtime,starttime,album,artist,category,question,choices,answer,points
  //callback from getYTList
  function updateQList(data) {
    var feed = data.feed;
    var entries = feed.entry || [];
    for (var i = 0; i < entries.length; i++) {
      var q = Object();
      var entry = entries[i];

      q.index = i+1;
      q.date = entry.updated.$t;
      var id = entry.id.$t;
      var j = id.lastIndexOf("/");
      q.vid = id.slice(++j);
      q.author = entry.author[0].name.$t;
      q.title = entry.title.$t;
      q.url = "http://www.youtube.com/v/" + q.vid;
      q.rating = entry.gd$rating.average;
      q.hits = entry.yt$statistics.viewCount;
      q.favorite = entry.yt$statistics.favoriteCount;
      q.starttime = 0;
      q.playtime = 10;
      q.duration = entry.media$group.yt$duration.seconds;
      q.category = entry.category[1].label;
      var obj = getRandomQ(q);
      q.question = obj.question;
      q.answer = obj.answer;
      q.choices = obj.choices.join(',');
      q.points = 100;
      qList.push(q);
    }

    qListLength = qList.length;

    $("#debug").append("getYTList: len " + qList.length + " \n");

    $("#next").button("option", "label", "Play");
    $("#next").unbind();
    $("#next").bind('click', startQ);
  }


  function getRandomQ(q) {
    var obj = new Object();
    var str = "";
    var choices = new Array();
    var randPos = Math.floor(Math.random()*5);
    //var type = ['rating', 'title', 'author', 'hits'];
    var type = ['favorite', 'rating', 'hits'];
    var randType = Math.floor(Math.random()*type.length);

    switch(type[randType]) {
      case 'rating':
        str = "Guess the average rating for this video on YouTube ?";
        for(var i=0; i<5; i++) {
          var randChoice = Math.random()*10;
          if(i == randPos) {
            choices[randPos] = q.rating.toFixed(5);
          }
          else {
            choices[i] = randChoice.toFixed(5);
          }
        }
        break;

      case 'favorite':
        str = "What is the favorite count for this video on YouTube ?";
        var len = q.favorite.length;
        var factor = 1;
        for(var i=0; i<len; i++) {
          factor = factor * 10;
        }
        for(var i=0; i<5; i++) {
          var randChoice = Math.floor(Math.random()*factor);
          if(i == randPos) {
            choices[randPos] = q.favorite;
          }
          else {
            choices[i] = randChoice;
          }
        }
        break;

      case 'hits':
        str = "How many time has this video been viewed on YouTube ?";
        var len = q.hits.length;
        var factor = 1;
        for(var i=0; i<len; i++) {
          factor = factor * 10;
        }
        for(var i=0; i<5; i++) {
          var randChoice = Math.floor(Math.random()*factor);
          if(i == randPos) {
            choices[randPos] = q.hits;
          }
          else {
            choices[i] = randChoice;
          }
        }
        break;

      case 'author':
        str = "Who is the author of this video ?";
        choices[randPos] = q.author;
        break;

      case 'title':
        str = "Guess the title of this video ?";
        for(var i=0; i<5; i++) {
          if(i == randPos) {
            choices[randPos] = q.title;
          }
          else {
            choices[i] = '';
          }
        }
        break;

      default:
        break;
    }

    obj.question = str;
    obj.choices = choices;
    obj.answer = randPos;
    return obj;
  }

  //get list of questions from our server
  //date,id,key,title,author,url,rating,hits,playtime,starttime,album,artist,category,question,choices,answer,points
  function getQList() {
    var str = "";
    $.ajax({
      type: "GET",
      url: "/get?start=" + startIndex + "&max=" + maxResult,
      dataType: "json",
      success: function(msg) {
        qList = msg;
        qListLength = qList.length;
        if (qListLength === 0) {
          resetQ("Game Over");
          $("#next").unbind();
          $("#next").hide();
          str += 'Thank you for using Kuch Bhi Kya !.<br>';
          str += 'We are constantly adding more questions. Please check again for more trivia.<br><br>';
          str += 'If you would like to try the quiz again, click below<br>';
          str += "<br><button id='reset-game'>Reset Quiz</button>";
          str += '<script type="text\/javascript">\$("#reset-game").button(); $("#reset-game").click(resetQuiz);<\/script>';
          $("#choices").html(str);
          $("#choices").show();
          postUserInfo();
        }
        else { 
          startIndex += maxResult;
          $("#next").button("option", "label", "Play");
          $("#next").unbind();
          $("#next").bind('click', startQ);
        }
      },
      error: function(msg) {
       alert( "error " + msg );
      }
    });
  }

  //go back to the first question. User will have to take all the questions again
  function resetQuiz() {
    resetQ("Hit Play for the next question");
    UserInfo.currQ = 1;
    startIndex = UserInfo.currQ;
    getQList();
  }

  //set the screen for steady state, no playing, no clicking except next
  //msg can be an object (undefined) or string, so set it appropriately to ""
  //if its undefined. Otherwise you will see the Hit next Q message unnecessarily
  function resetQ(msg) {
    $("#debug").append("resetQ: \n");

    //stop video if running
    if(ytplayer) {
      ytplayer.stopVideo();
    }

    //hide question and choice boxes
    $("#question").hide();
    $("#choices").hide();

    //unbind the submit button
    $("#choice").unbind();
    $("#choice").hide();

    //stop the countdown timer
    stopCountDown();

    $("#debug").append("resetQ: " + typeof msg + " \n");

    if(!msg) {
      msg = "";
    }

    if(typeof msg != 'string') {
      msg = "Hit Play for the next Question";
    }

    $("#player_ol").html("<h3 class='countdown'>" + msg + "</h3>");
    $("#player_ol").show();

    $("#next").button("option", "label", "Play");
    $("#next").unbind();
    $("#next").bind('click', startQ);
    $("#next").show();
  }

  function startQ() {
    if(qList.length ==  0) {
      $("#debug").append("You are done or get more\n");
      resetQ("Get Next " + maxResult + " Questions");
      $("#next").button("option", "label", "Get More");
      $("#next").unbind();
      $("#next").bind('click', getQList);
      //update the last answered question index so next 
      //getQList will get a different set of questions
      currIndex = 0;
      postUserInfo();
      return 0;
    }
    else {
      resetQ();
      $("#next").button("option", "label", "Skip");
      $("#next").unbind();
      $("#next").bind('click', function () {
        UserInfo.miss++;
        updateStatus();
        resetQ("Hit Play for next Question");
      });
      currQ = qList.shift();
      currIndex++;
      UserInfo.currQ++;
    }


    //hide the player overlay
    $("#player_ol").hide('clip');

    //start the video
    var url = "http://www.youtube.com/v/" + currQ.vid;

    $("#debug").append("startQ: " + url + " " + currQ.starttime + " \n");
    ytplayer.loadVideoByUrl(url, currQ.starttime);

    $("#question").html("Question " + currIndex + " of " + qListLength);
    $("#question").show();

    //start the timer
    //since buffering can take a long time, we want to start
    //the timer when the player get to playing state. see above
  }

  function stopQ() {
    $("#debug").append("stopQ: intTime " + intTime + " \n");

    ytplayer.stopVideo();

    //create and show question and choices
    showQuestion();
    fillChoices();
    $("#choices").slideDown('slow');

    //get ready for an answer
    $("#choice").bind('click', checkAnswer);
    $("#choice").show();

    $("#next").unbind();
    $("#next").hide();

    //display overlay with countdown and start countdown
    $("#player_ol").html('<h1 class="countdown">' + cntDown + '</h1>');
    if(!intTime) {
      intTime = setInterval("startCountDown()", 1000); 
    }
    $("#player_ol").show('clip', 1000);
  }

  function startCountDown() {
    if (cntDown == 15) {
      $("#debug").append("startCD " + cntDown + "\n");
    }

    $("#player_ol").html('<h1 class="countdown">' + cntDown + '</h1>');
    cntDown--;

    if (cntDown == -1) {
      //stopCountDown();
      //$("#player_ol").html("<h3 class='countdown'>Time Up!</h3>");
      resetQ("Time Up!");
      showAnswer();
      UserInfo.miss++;
      updateStatus();
    }
  }

  function stopCountDown() {
    $("#debug").append("stopCD " + intTime + " \n");

    if(intTime) {
      clearInterval(intTime);
      intTime = null;
    }
    if(timeout) {
      clearTimeout(timeout);
      timeout = null;
    }
    cntDown = 15;
  }

  function fillChoices() {
    var arr = currQ.choices.split(',');
    var str = "";

    for (var i = 0; i < arr.length; i++ ) {
      str += "<input type='radio' name='answers' value='" + i + "'>" + arr[i] + "<br>";
    }
    $("#choices").html(str);
  }

  function showQuestion() {
    $("#question").html(currQ.question);
    $("#question").slideDown('slow');
  }

  function checkAnswer() {
    var msg = "";
    var v = $('input:radio[name=answers]:checked').val();
    if (v == currQ.answer) {
        UserInfo.score += currQ.points;
        UserInfo.hits++;
        msg = "That's right !<br>Score: " + UserInfo.score;
    }
    else {
        msg = "Kuch Bhi Kya !";
        UserInfo.miss++;
    }
    updateStatus();
    postUserInfo();
    resetQ(msg);
    showAnswer();
  }

  function showAnswer() {
    var str = "";
    var arr = currQ.choices.split(',');
    for (var i = 0; i < arr.length; i++ ) {
      if(i == currQ.answer) {
        str = arr[i];
      }
    }
    str += "<br><br><br><button id='fullvideo'>Watch Full Video</button>";
    str += '<script type="text\/javascript">\$("#fullvideo").button(); $("#fullvideo").click(fullVideo);<\/script>';
    $("#choices").html("Answer: " + str);
    $("#choices").show();
    showQuestion();
  }

  function fullVideo() {
    //hide the player overlay
    $("#player_ol").hide();
    $("#choices").html();

    //start the video
    var url = "http://www.youtube.com/v/" + currQ.vid;
    currQ.playtime = currQ.duration+1;
    ytplayer.loadVideoByUrl(url, 0);
  }

  function getUserInfo() {
    var uid = UserInfo.uid;
    var uname = UserInfo.name;
    $.ajax({
       type: "GET",
       url: "/put?uid=" + uid,
       dataType: "json",
       success: function(msg) {
         $("#debug").append("success getUserinfo: uid=" + msg.uid + " score= " + msg.score + " name= " + msg.name + "<br>");
          UserInfo=msg;
          //if no such user is present, indicated by uid==0, reset the uid to what we got from FB
          if(UserInfo.uid == 0) {
            UserInfo.uid = uid;
            UserInfo.name = uname;
            postUserInfo();
          }
          startIndex = UserInfo.currQ;
          getQList();
          updateStatus();
       },
       error: function(msg) {
         $("#debug").append("error getUserinfo " + msg + "<br>");
       }
     });
  }

  function postUserInfo() {
    $.ajax({
       type: "POST",
       url: "/put",
       data: JSON.stringify(UserInfo),
       success: function(msg) {
         $("#debug").append("success postUserinfo " + msg + "<br>");
       },
       error: function(msg) {
         $("#debug").append("error postUserinfo " + msg + "<br>");
       }
     });
  }
</script>
</head>

<body>

<div id="fb-root"></div>
<script>
  window.fbAsyncInit = function() {
    FB.init({
      appId  : '159760274050584',
      status : true, // check login status
      cookie : true, // enable cookies to allow the server to access the session
      xfbml  : true  // parse XFBML
    });

    FB.Event.subscribe('auth.sessionChange', checkStatus);
    FB.getLoginStatus(checkStatus);
  };

  function checkStatus(response) {
    if (response.status == "connected") {
        getMe();
        $("#login-button").hide();
    } 
    else if (response.status == "notConnected") {
        UserInfo.uid = 0;
        getQList();
        $("#login-button").show();
    }
  }

  //gets the current user info
  function getMe() {
    FB.api('/me', function(response) {
        UserInfo.uid = response.id;
        UserInfo.name = response.name;
        getUserInfo();
    });
  }


  (function() {
    var e = document.createElement('script');
    e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
    e.async = true;
    document.getElementById('fb-root').appendChild(e);
  }());
</script>

<div id="content" style="position: relative;">
  <div id="header" class="headerarea ui-corner-all">
    <div id="status-area">
      <div id="login-button" style="float: left;">
        <fb:login-button></fb:login-button>
      </div>
      <div id="status" style="float: left; margin-left: 90;">
      </div>
      <div id="status-score" style="float: right; padding: 2 5 5 5; color: #333">
      </div>
    </div>
  </div>
  <div id="player" class="ui-corner-all playarea general">
    <div id="ytapiplayer">
      You need Flash player 8+ and JavaScript enabled to view this video.
    </div>
  </div>
  <div id="player_ol" class="ui-corner-all playarea_ol general">
    <h3 class='countdown' style="font-size: 35px; color: #333">Welcome to Bollywood Trivia</h3>
    <h3 class='countdown'>Kuch Bhi Kya !</h3>
  </div>


  <div id="qa" class="general ui-corner-all qaarea">
    <div id="question-area" style="padding: 8; height: 24;" class="ui-widget-header ui-corner-all">
      <div id="question">
      Brings you closer to the movies you love !
      </div>
    </div>
    <div id="choices-area" style="padding: 8; height: 120; margin: 10 0 10 0;" class="ui-widget-content ui-corner-all">
      <div id="choices">
        Enjoy the clips and answer the question to win points
      </div>
    </div>
    <button id="choice" style="width: 100%;">Submit</button>
    <button id="next" style="width: 100%;">Play</button>
  </div>

  <div class="debug-area ui-corner-all">
    <pre id="debug1"> 
    </pre>
    <pre id="debug"> 
    debug
    </pre>
  </div>
</div>

</body>
</html>
